<template>
  <div class="relationship-container">
    <div class="flex justify-content-space-between">
      <div class="flex-auto">
        <div class="header flex justify-content-space-between align-center"
             style="background-color: #FFFFFF;padding: 16px 20px;border-top-left-radius: 5px;border-top-right-radius: 5px;">
          <div class="flex align-center">
            <img alt="" class="border" src="" style="width: 30px;height: 30px;display: block">
            <div style="margin-left: 10px;font-size: 18px;font-weight: bolder;color: #333">显示组织关系</div>
          </div>
          <el-button icon="Plus" style="margin: 0 10px" type="primary" @click="handleAdd">新增组织</el-button>
        </div>
        <div :style="{ 'min-height': organizationTree.length === 0 ? 'calc(100vh - 174px)' : '100%',
                         'padding-left': '20px',
                         'box-sizing': 'border-box',
                         'padding-top': '10px'}"
             class="tree-container">
          <el-tree
              :data="organizationTree"
              :default-expand-all="true"
              :expand-on-click-node="false"
              :props="defaultProps"
              class="custom-tree"
              empty-text="暂无任何组织"
              node-key="name"
              style="
                 padding-left: 20px;
                 box-sizing: border-box;
                 padding-top: 10px"
              @node-click="handleNodeClick">
            <template #default="{ node, data }">
              <div class="custom-tree-node flex align-center">
                <img :src="getIconByNodeType(data, node)" class="tree-node-icon"/>
                <div>{{ node.label }}</div>
                <div :style="getCountStyle(data)" style="margin-left: 20px;font-size: 14px;color: #6E7582">
                  ({{ data.countUserSum }}人)
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
      <div style="margin-left: 20px;width: 600px">
        <div class="header flex justify-content-space-between "
             style="background-color: #FFFFFF;padding: 16px 20px;border-top-left-radius: 5px;border-top-right-radius: 5px;">
          <div class="flex">
            <img alt="" class="border" src="" style="width: 30px;height: 30px;display: block">
            <div style="margin-left: 10px;font-size: 18px;font-weight: bolder;color: #333">党组织详细信息</div>
          </div>
        </div>
        <div :style="{ 'min-height': organizationTree.length === 0 ? 'calc(100vh - 174px)' : '100%','padding-left': '20px','box-sizing': 'border-box','padding-top': '10px'}"
             class="part-container">
          <div class="organization-info-card">
            <!-- 组织名称 -->
            <div class="title">
              <span>{{ organization.name }}</span>
              <div class="action-buttons">
                <el-button plain size="small" type="danger" @click="handleEdit">
                  <el-icon>
                    <Edit/>
                  </el-icon>
                  编辑
                </el-button>
                <el-button plain size="small" type="danger" @click="handleDelete">
                  <el-icon>
                    <Delete/>
                  </el-icon>
                  删除
                </el-button>
              </div>
            </div>

            <!-- 组织编码 -->
            <div class="info-item">
              <span class="label">组织编码:</span>
              <span class="value">{{ organization.code }}</span>
            </div>

            <!-- 成立时间 & 组织类型 -->
            <div class="info-row">
              <div class="info-item">
                <div class="label">成立时间</div>
                <div class="value">{{ organization.establishDate }}</div>
              </div>
              <div class="info-item">
                <div class="label">组织类型</div>
                <div class="value">{{ organization.type }}</div>
              </div>
            </div>
            <!-- 上级组织 & 组织状态 -->
            <div class="info-row">
              <div class="info-item">
                <div class="label">上级组织</div>
                <div class="value">{{ organization.parentName }}</div>
              </div>
              <div class="info-item">
                <div class="label">组织状态</div>
                <div :class="['status', statusClass]">{{ organization.status }}</div>
              </div>
            </div>
            <!-- 负责人信息 -->
            <div class="section-title">负责人信息</div>
            <div class="leader-info">
              <div class="avatar">
                <el-avatar :size="40" :src="organization.leaderAvatar || 'https://via.placeholder.com/40'">
                  {{ organization.leaderName?.charAt(0) }}
                </el-avatar>
              </div>
              <div class="leader-details">
                <div class="name">{{ organization.leaderName }}</div>
                <div class="position">{{ organization.leaderPosition }}</div>
                <div class="id">{{ organization.leaderId }}</div>
              </div>
            </div>
            <!-- 党员统计 -->
            <div class="section-title">党员统计</div>
            <div class="statistics">
              <div class="stat-item">
                <div class="number">{{ organization.totalMembers }}</div>
                <div class="label">党员总数</div>
              </div>
              <div class="stat-item">
                <div class="number">{{ organization.fullMembers }}</div>
                <div class="label">正式党员</div>
              </div>
              <div class="stat-item">
                <div class="number">{{ organization.probationaryMembers }}</div>
                <div class="label">预备党员</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 党组织信息弹窗 -->
    <el-dialog v-model="visible" :title="isEdit ? '编辑党组织' : '新增党组织'" width="1200" @close="handleClose">
      <div style="color: #727986;margin-bottom: 10px">请填写组织相关信息，带* 为必填项</div>
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="top" size="default">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 上级组织 -->
            <el-form-item label="上级组织" prop="organizationParentId">
              <el-tree-select v-model="formData.organizationParentId" :check-strictly=true :props="{value: 'id', label: 'organizationName',children: 'children'}" :data="organizationTree" :render-after-expand="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 组织类型 -->
            <el-form-item label="组织类型" prop="organizationTypeId">
              <el-select v-model="formData.organizationTypeId" placeholder="请选择组织类型" style="width: 100%">
                <el-option :label="item.pbOrganizationTypeName"  v-for="(item,index) in organizationType"  :key="index" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 组织名称 -->
            <el-form-item label="组织名称" prop="organizationName">
              <el-input v-model="formData.organizationName" placeholder="请输入组织名称" style="width: 100%"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 组织编码 -->
            <el-form-item label="组织编码" prop="organizationCode">
              <el-input v-model="formData.organizationCode" placeholder="请输入组织编码" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 成立时间 -->
            <el-form-item label="成立时间" prop="organizationTime">
              <el-date-picker v-model="formData.organizationTime" format="YYYY年MM月DD日" placeholder="选择日期" style="width: 100%" type="date" value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 组织状态 -->
            <el-form-item label="组织状态" prop="organizationState">
              <el-select v-model="formData.organizationState" placeholder="请选择组织状态" style="width: 100%">
                <el-option label="已撤销" :value="0"/>
                <el-option label="正常" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 组织简介 -->
        <el-form-item label="组织简介" prop="organizationSummary">
          <el-input v-model="formData.organizationSummary" :rows="4" placeholder="请输入组织简介" style="width: 100%" type="textarea"/>
        </el-form-item>

        <!-- 负责人信息 -->
        <div class="section-title" style="padding-bottom: 10px">负责人信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" prop="organizationUserName">
              <el-input v-model="formData.organizationUserName" placeholder="请输入姓名" style="width: 100%"/>
            </el-form-item>
          </el-col>


          <el-col :span="8">
            <el-form-item label="职务" prop="organizationPosition">
              <el-input v-model="formData.organizationPosition" placeholder="请输入职务" style="width: 100%"/>
 <!--             todo... 职务应该是下拉选择才是,为何要选择输入框？？？
                  <el-select v-model="formData.organizationState" placeholder="请选择组织状态" style="width: 100%">-->
<!--                <el-option v-for="item in partyStatusList" :key="item.id" :label="item.stateName" :value="item.id"></el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>



          <el-col :span="8">
            <el-form-item label="联系电话" prop="organizationPhone">
              <el-input v-model="formData.organizationPhone" placeholder="请输入联系电话" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSubmit">{{ isEdit ? '确认修改' : '确认新增' }}</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import {ref} from 'vue';
import {ElMessage, ElMessageBox} from "element-plus";
import {getPBStateList} from "@/api/partyMemberInfo/partyMemberInfo.js";
import {
  createOrganization, delOrganization,
  getOrganizationType,
  getPBOrganizationTree,
  updateOrganization
} from "@/api/relationship/relationship.js";
// 组织树数据 - 树形结构
const organizationTree = ref([]);
const defaultProps = {
  children: 'children',
  label: 'organizationName',
}
const organizationType = ref([]);
const partyStatusList = ref([]);
const isEdit = ref(false); // 新增 OR 编辑


// 根据节点类型获取对应图标
const getIconByNodeType = (data, node) => {
  // 根节点
  if (!node.parent || node.level === 1) {
    return new URL('../../../assets/icons/custIcon/空心圆.png', import.meta.url).href;
  }
  // 支部节点
  else if (data.organizationName.includes('支部')) {
    return new URL('../../../assets/icons/custIcon/空心圆.png', import.meta.url).href;
  }
  // 党小组节点
  else if (data.organizationName.includes('党小组')) {
    return new URL('../../../assets/icons/custIcon/实心.png', import.meta.url).href;
  }
  // 默认节点
  else {
    return new URL('../../../assets/icons/custIcon/实心.png', import.meta.url).href;
  }
}
// 根据人数返回样式
const getCountStyle = (data) => {
  if (data.count >= 40) {
    return {color: '#f56c6c'}; // 红色 - 人数很多
  } else if (data.count >= 20) {
    return {color: '#bbbbbb'}; // 橙色 - 人数较多
  } else if (data.count >= 10) {
    return {color: '#bbbbbb'}; // 绿色 - 人数适中
  } else {
    return {color: '#bbbbbb'}; // 灰色 - 人数较少
  }
}
// 处理节点点击事件
const handleNodeClick = (data, node, component) => {
  console.log('点击的节点数据:', data);
  console.log('节点对象:', node);
  console.log('组件实例:', component);
}
// 组件数据
const organization = ref({
  name: '内科支部',
  code: 'NKZB2023001',
  establishDate: '2015年7月1日',
  type: '机关党委',
  parentName: '桂林市人民医院党支部',
  status: '正常',
  leaderName: '张建国',
  leaderPosition: '党委书记',
  leaderId: '13800138000',
  countUserSum: 24,
  fullMembers: 15,
  probationaryMembers: 9,
  leaderAvatar: null // 可以设置头像URL
});
// 计算状态样式
const statusClass = computed(() => {
  return organization.status === '正常' ? 'normal' : 'abnormal';
});
// 处理编辑事件
const handleEdit = () => {
  console.log('编辑组织:', organization);
  isEdit.value = true; // 编辑状态
  visible.value = true
};


// 处理删除事件
const handleDelete = () => {
  console.log('删除组织:', organization);
  ElMessageBox.confirm(
      '是否删除党支部?',
      '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    let result = await delOrganization("3a1bfed1-20f1-bf31-2cc8-bcd74a4c9da6");
    if (result.status == 200 && result.data.code == 200){
      ElMessage({type: 'success', message: '删除成功！'});
      await getPBOrganizationTreeList();
    }else {
      ElMessage({type: 'error', message: '删除失败！'});
    }
  }).catch(() => {
    ElMessage({type: 'info', message: '取消删除！'});
  })

};



const editData = ref({});
const parentOrganizations = ref([]);
// 定义事件
const emits = defineEmits(['confirm', 'cancel']);
// 弹窗显示状态
const visible = ref(false);

// 表单数据
const formData = ref({
  organizationName: '测试组织001', //组织名称
  organizationTypeId: '3a1bbe7a-6ae8-2bac-2787-b265fdb9eb1a', // 组织类型
  organizationParentId: '3a1bbe7a-6ae8-2bac-2787-b265fdb9eb1a', // 上级组织ID
  organizationCode: '170422432', // 组织编码
  organizationTime: '2025-08-24', // 成立时间
  organizationState: 0, // 组织状态
  organizationSummary: '组织简介.......', // 组织简介
  organizationUserName: '张心心', // 负责人名称
  organizationPosition: '支部书记',  // 负责人职位
  organizationPhone: '18920405770', // 负责人手机
});

// 表单验证规则
const rules = {
  organizationParentId: [{required: true, message: '请选择上级组织', trigger: 'change'}],
  organizationTypeId: [{required: true, message: '请选择组织类型', trigger: 'change'}],
  organizationName: [
    {required: true, message: '请输入组织名称', trigger: 'blur'},
    {min: 2, max: 50, message: '长度在 2 到 50 个字符之间', trigger: 'blur'}
  ],
  organizationCode: [
    {required: true, message: '请输入组织编码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符之间', trigger: 'blur'}
  ],
  organizationTime: [{required: true, message: '请选择成立时间', trigger: 'change'}],
  organizationState: [{required: true, message: '请选择组织状态', trigger: 'change'}],
  organizationUserName: [
    {required: true, message: '请输入负责人姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur'}
  ],
  organizationPosition: [
    {required: true, message: '请输入职务', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符之间', trigger: 'blur'}
  ],
  organizationPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ]
};

// 加载状态
const loading = ref(false);

// 表单引用
const formRef = ref(null);

// 打开弹窗
const handleAdd = (data = null) => {
  if (data && isEdit.value) { // 编辑模式，填充表单数据
    Object.assign(formData, data);
  } else {
    // 新增模式，重置表单
    resetForm();
  }
  isEdit.value = false;
  visible.value = true;
};

// 关闭弹窗
const handleClose = () => {
  if (loading.value) return;
  handleCancel();
};

// 取消操作
const handleCancel = () => {
  visible.value = false;
  emits('cancel');
};



// 重置表单
const resetForm = () => {
      formData.value.organizationName = '';
      formData.value.organizationTypeId = '';
      formData.value.organizationParentId = '';
      formData.value.organizationCode = '';
      formData.value.organizationTime = '';
      formData.value.organizationState = '';
      formData.value.organizationSummary = '';
      formData.value.organizationUserName = '';
      formData.value.organizationPosition = '';
      formData.value.organizationPhone = '';
      if (formRef.value) {
         formRef.value.resetFields();
      }
};


// API接口组织树

// 获取组织树
const getPBOrganizationTreeList = async () => {
  let result = await getPBOrganizationTree();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
    organizationTree.value = data;
    console.log(organizationTree.value )
  }
}

// 获取组织类型列表
const getOrganizationTypeList = async () => {
  let result = await getOrganizationType();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
    organizationType.value = data;
  }
}

// 获取职务信息
const getPBState = async () => {
  let result = await getPBStateList();
  let data = result.data.data;
  if (result.status == 200 && result.data.code == 200){
     partyStatusList.value = data
  }
}

// 编辑和修改组织,提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    let result = null;
    console.log("党新增和修改的数据......",formData.value)
    if (isEdit.value === true){
       result = await createOrganization(formData.value);
    }else {
       result = await updateOrganization(formData.value);
    }
    if (result.status == 200 && result.data.code == 200){
       ElMessage.success(isEdit.value ? '修改成功' : '新增成功');
       loading.value = false;
       visible.value = false;
    }else {
      ElMessage.error(isEdit.value ? '修改失败' : '新增失败');
      loading.value = false;
    }
  } catch (error) {
    loading.value = false;
  }
};




getPBState()
getPBOrganizationTreeList();
getOrganizationTypeList()

</script>
<style lang='scss' scoped>
.relationship-container {
  height: calc(100% - 40px);
  box-sizing: border-box;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
  margin: 20px;
  //background-color: #FFFFFF;
  border-radius: 5px;

  .tree-container {
    /* 1. 背景图：保持原图片链接 */
    background-image: linear-gradient(to right,
        rgb(255, 255, 255) 0%, /* 左侧起点：完全不透明（遮挡背景图） */
        rgba(255, 255, 255, .7) 90%, /* 左侧起点：完全不透明（遮挡背景图） */
        rgba(255, 255, 255, 0) 100% /* 右侧终点：完全透明（显示背景图） */
    ),
    url("https://pic.rmb.bdstatic.com/bjh/240403/material/156d40e73d2b17314acd48742226814e6124.jpeg");

    /* 2. 背景图基础配置（避免拉伸/重复） */
    background-size: cover; /* 背景图覆盖容器，保持比例 */
    background-position: center; /* 背景图居中显示 */
    background-repeat: no-repeat; /* 背景图不重复 */

    /* 3. 可选：控制渐变过渡范围（如需更窄的透明区域） */
    /* 例：前 60% 透明，后 40% 渐变到不透明 */
    //linear-gradient(to right, rgba(255,255,255,0) 60%, rgba(255,255,255,1) 100%);
    margin-top: 1px;

  }

  .tree-node-icon {
    width: 10px;
    height: 10px;
    margin-right: 20px;
  }

  .custom-tree {
    background-color: transparent;

    :deep(.el-tree-node__expand-icon) {
      display: none;
    }

    :deep(.el-tree-node__content) {
      height: 100%;
    }

    :deep(.el-tree-node) {
      padding: 6px 0;
      font-size: 16px;
    }
  }

  .part-container {
    border-top: 1px solid #f6f1f1;
    margin-top: 1px;
    background-color: #FFFFFF;
    padding: 20px;
  }

  .organization-info-card {
    margin-top: 20px;
    background-color: #ffffff;
    border-radius: 8px;
    padding: 30px;
    box-sizing: border-box;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border: 1px solid #ebeef5;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      span {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
    }

    .action-buttons {
      display: flex;
      gap: 8px;
    }

    .info-item {

      flex: 1;

      .label {
        width: 80px;
        color: #909399;
        font-size: 14px;
        margin-right: 8px;
      }

      .value {
        flex: 1;
        color: #333;
        font-size: 14px;
      }
    }

    .info-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
    }

    .section-title {
      font-size: 14px;
      color: #909399;
      margin: 40px 0 8px;
      font-weight: 500;

    }

    .leader-info {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .avatar {
        margin-right: 12px;
      }

      .leader-details {
        .name {
          font-size: 16px;
          color: #333;
          margin-bottom: 4px;
        }

        .position {
          font-size: 14px;
          color: #909399;
          margin-bottom: 4px;
        }

        .id {
          font-size: 14px;
          color: #909399;
        }
      }
    }

    .statistics {
      display: flex;
      gap: 12px;

      .stat-item {
        flex: 1;
        text-align: center;
        padding: 12px;
        background-color: #f5f7fa;
        border-radius: 6px;

        .number {
          font-size: 20px;
          font-weight: bold;
          color: #f56c6c;
          margin-bottom: 4px;
        }

        .label {
          font-size: 12px;
          color: #909399;
        }
      }
    }

    .status {
      &.normal {
        color: #409eff;
        font-weight: 500;
      }

      &.abnormal {
        color: #f56c6c;
        font-weight: 500;
      }
    }
  }
}

.custom-tree {
  :deep(.el-tree-node__content) {
    &:hover {
      background-color: #f6f6f6 !important; // 自定义悬浮颜色
    }
  }
}
</style>
